package com.z6pin.controller;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by jiaobuchong on 12/23/15.
 */
@Aspect // 定义一个切面
@Configuration
public class LogRecordAspect {
	private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);

	private String requestPath = null; // 请求地址
	private String userName = null; // 用户名
	private Map<?, ?> inputParamMap = null; // 传入参数
	private Map<String, Object> outputParamMap = null; // 存放输出结果
	private long startTimeMillis = 0; // 开始时间
	private long endTimeMillis = 0; // 结束时间

	@Before("execution(* com.z6pin.controller..*.*(..))")
	public void doBeforeInServiceLayer(JoinPoint joinPoint) {
		startTimeMillis = System.currentTimeMillis(); // 记录方法开始执行的时间
		System.out.println("before invoke controller");
	}

	@After("execution(* com.z6pin.controller..*.*(..))")
	public void doAfterInServiceLayer(JoinPoint joinPoint) {
		endTimeMillis = System.currentTimeMillis(); // 记录方法执行完成的时间
		System.out.println("after invoke controller");
	}

	@Around("execution(* com.z6pin.controller..*.*(..))")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		Object result = null;
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			ServletRequestAttributes sra = (ServletRequestAttributes) ra;
			HttpServletRequest request = sra.getRequest();
	
			String url = request.getRequestURL().toString();
			
			MethodSignature signature = (MethodSignature) pjp.getSignature();
	        String methodName = signature.getMethod().getName();
			
			String method = request.getMethod();
			String uri = request.getRequestURI();
			String queryString = request.getQueryString();
			logger.info("参数, url: {}, method: {}, uri: {}, params: {}", url, methodName, uri, queryString);
			System.out.println("参数, url: {}, method: {}, uri: {}, params: {}" + "  " + url + "  " + methodName + "  "
					+ uri + "  " + queryString);
			// result的值就是被拦截方法的返回值
			result = pjp.proceed();
	
			System.out.println("返回值是 " + result);
			logger.info("返回值是 " + result);
		}catch(Exception e) {
			
		}
		return result;
	}
}